package com.sap.com.seckill.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.sap.com.seckill.feign.CouponFeignService;
import com.sap.com.seckill.feign.ProductFeignService;
import com.sap.com.seckill.interceptor.LoginUserInterceptor;
import com.sap.com.seckill.service.SeckillService;
import com.sap.com.seckill.to.SeckillSkuRedisTO;
import com.sap.com.seckill.vo.SeckillSessionWithSkus;
import com.sap.com.seckill.vo.SkuInfoVo;
import com.sap.common.to.mq.SeckillOrderTo;
import com.sap.common.utils.R;
import com.sap.common.vo.MemberRespVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {

    private final String SESSION_CACHE_PREFIX = "seckill:sessions:";
    private final String SKUKILL_CACHA_PREFIX = "seckill:skus";
    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";

    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    RedissonClient redissonClient;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public void uploadSeckillSkuLatest3Days() {
        //1、扫描需要参与秒杀的活动
        R session = couponFeignService.getLatest3DaysSession();
        if (session.getCode() == 0) {
            List<SeckillSessionWithSkus> sessionData = session.getData(new TypeReference<List<SeckillSessionWithSkus>>() {
            });
            // 缓存到redis
            if (CollectionUtils.isNotEmpty(sessionData)) {
                // 缓存活动信息
                saveSessionInfos(sessionData);
                // 缓存活动的关联商品信息
                saveSessionSkuInfos(sessionData);
            }
        }
    }

    /**
     * blockHandler 针对限流、降级时调用
     *
     * fallback     针对所有类型的异常
     *
     * @param e
     * @return
     */
    public List<SeckillSkuRedisTO> blockHandler(BlockException e){
        log.error("getCurrentSeckillSkusResource被限流了=>{}",e.getMessage());
        return null;
    }
    /**
     * 返回当前时间按可以参与得秒杀商品
     *
     * @return
     */
    @SentinelResource(value = "getCurrentSeckillSkusResource",blockHandler = "blockHandler",fallback = "")
    @Override
    public List<SeckillSkuRedisTO> getCurrentSeckillSkus() {
        long time = new Date().getTime();
        try (Entry entry = SphU.entry("seckillSkus")){
            // 1、确定当前时间属于哪个秒杀场次
            // 2、获取所有redis得场次
            Set<String> keys = redisTemplate.keys(SESSION_CACHE_PREFIX + "*");
            for (String key : keys) {
                String replace = key.replace(SESSION_CACHE_PREFIX, "");
                String[] s = replace.split("_");
                Long start = Long.parseLong(s[0]);
                Long end = Long.parseLong(s[1]);
                if (time >= start && time <= end) {
                    // 3、获取这个场次需要得所有商品信息
                    List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                    BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHA_PREFIX);
                    List<String> list = hashOps.multiGet(range);
                    if (list != null && list.size() > 0) {
                        List<SeckillSkuRedisTO> collect = list.stream().map(item -> {
                            SeckillSkuRedisTO redisTO = JSON.parseObject(item, SeckillSkuRedisTO.class);
//                        redisTO.setRandomCode(null); 当前秒杀开始需要随机码
                            return redisTO;
                        }).collect(Collectors.toList());
                        return collect;
                    }
                }
            }
        } catch (BlockException e) {
            log.info("自定义流控 {}",e.getMessage());
        }

        return null;
    }

    @Override
    public SeckillSkuRedisTO getSkuSeckillInfo(Long skuId) {
        // 1、找到所有需要参与秒杀得商品得key
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHA_PREFIX);
        Set<String> keys = hashOps.keys();
        if (CollectionUtils.isNotEmpty(keys)) {
            String regx = "\\d_" + skuId;
            for (String key : keys) {
                if (Pattern.matches(regx, key)) {
                    String json = hashOps.get(key);
                    SeckillSkuRedisTO skuRedisTO = JSON.parseObject(json, SeckillSkuRedisTO.class);
                    Long current = new Date().getTime();
                    if (current >= skuRedisTO.getStartTime() && current <= skuRedisTO.getEndTime()) {
                    } else {
                        skuRedisTO.setRandomCode(null);
                    }
                    return skuRedisTO;
                }
            }
        }
        return null;
    }

    // TODO: 3/13/2021  上架秒杀商品的时候，每一个数据都有过时时间
    // TODO: 3/13/2021  秒杀后续的流程，简化了收货地址等信息
    @Override
    public String seckill(String killId, String key, Integer num) {
        long s1 = System.currentTimeMillis();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        // 1、获取秒杀商品得详细信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHA_PREFIX);
        String s = hashOps.get(killId);
        if (StringUtils.isEmpty(s)) {
            return null;
        } else {
            SeckillSkuRedisTO redisTO = JSON.parseObject(s, SeckillSkuRedisTO.class);
            // 1、校验合法性
            Long startTime = redisTO.getStartTime();
            Long endTime = redisTO.getEndTime();
            long current = new Date().getTime();
            // 校验时间合法性
            if (current >= startTime && current <= endTime) {
                //2、校验随机码和商品id是否
                String randomCode = redisTO.getRandomCode();
                String skuId = redisTO.getPromotionSessionId() + "_" + redisTO.getSkuId();
                if (randomCode.equals(key) && killId.equals(skuId)) {
                    // 3、验证购物得数量是否合理
                    if (num <= redisTO.getSeckillCount()) {
                        // 4、验证这个人是否一i纪念馆购买过，幂等性，如果秒杀成功，就去占位 userId_sessionId_skuId
                        // setnx
                        String redisKey = memberRespVo.getId() + "_" + redisTO.getPromotionSessionId() + "_" + redisTO.getSkuId();
                        // 自动过期
                        long ttl = endTime - startTime;
                        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                        if (aBoolean) {
                            // 如果占位成功说明从来没有买过
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                            boolean b = semaphore.tryAcquire(num);
                            if (b) {
                                // 秒杀成功
                                // 快速下单，发送mq消息
                                String orderSn = IdWorker.getTimeId();
                                SeckillOrderTo seckillOrderTo = new SeckillOrderTo();
                                seckillOrderTo.setOrderSn(orderSn);
                                seckillOrderTo.setMemberId(memberRespVo.getId());
                                seckillOrderTo.setNum(num);
                                seckillOrderTo.setSkuId(redisTO.getSkuId());
                                seckillOrderTo.setPromotionSessionId(redisTO.getPromotionSessionId());
                                seckillOrderTo.setSeckillPrice(redisTO.getSeckillPrice());
                                rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", seckillOrderTo);
                                long s2 = System.currentTimeMillis();
                                log.info("秒杀耗时{}", (s2 - s1));
                                return orderSn;
                            }
                            return null;
                        } else {
                            return null;
                        }
                    }
                } else {

                }
            } else {
                return null;
            }
        }
        return null;
    }

    private void saveSessionInfos(List<SeckillSessionWithSkus> sessions) {
        sessions.stream().forEach(session -> {
            Long startTime = session.getStartTime().getTime();
            Long endTime = session.getEndTime().getTime();
            String key = SESSION_CACHE_PREFIX + +startTime + "_" + endTime;
            Boolean hasKey = redisTemplate.hasKey(key);
            if (!hasKey) {
                List<String> collect = session.getRelationSkus().stream().map(item -> item.getPromotionSessionId() + "_" + item.getSkuId().toString()).collect(Collectors.toList());
                // 缓存活动信息
                redisTemplate.opsForList().leftPushAll(key, collect);
            }
        });
    }

    private void saveSessionSkuInfos(List<SeckillSessionWithSkus> sessions) {
        BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKUKILL_CACHA_PREFIX);
        sessions.stream().forEach(session -> {
            session.getRelationSkus().stream().forEach(seckillSkuVo -> {
                String token = UUID.randomUUID().toString().replace("-", "");
                String key = seckillSkuVo.getPromotionSessionId() + "_" + seckillSkuVo.getSkuId().toString();
                if (!ops.hasKey(key)) {
                    // 缓存商品
                    SeckillSkuRedisTO redisTO = new SeckillSkuRedisTO();
                    // 1、sku的基本数据
                    R skuInfo = productFeignService.skuInfo(seckillSkuVo.getSkuId());
                    if (skuInfo.getCode() == 0) {
                        SkuInfoVo sku = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        redisTO.setSkuInfo(sku);
                    }
                    // 2、sku的秒杀信息
                    BeanUtils.copyProperties(seckillSkuVo, redisTO);

                    // 3、设置当前商品的秒杀时间信息
                    redisTO.setStartTime(session.getStartTime().getTime());
                    redisTO.setEndTime(session.getEndTime().getTime());

                    // 4、随机码 seckill?skuId=1&key=aba
                    redisTO.setRandomCode(token);
                    String s = JSON.toJSONString(redisTO);
                    ops.put(key, s);

                    // 如果当前这个场次得商品得库存信息已经上架就不需要上架
                    // 5、使用库存作为分布式信号量 限流；
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    // 商品可以秒杀的数量作为信号量
                    semaphore.trySetPermits(seckillSkuVo.getSeckillCount());
                }
            });
        });
    }
}
